package cn.zs.supply.common.utils;

import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;


public class InsuranceServiceClient {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(InsuranceServiceClient.class);
	
	public static JSONObject send(String url, JSONObject param) {
		
		return doPost(url,param,true);
	}
	
	public static JSONObject post(String url, JSONObject param) {
		
		return doPost(url,param,false);
	}

	private static JSONObject doPost(String url, JSONObject param, boolean getData) {
		HttpPost post = new HttpPost(url);
		//设置请求头格式
		post.addHeader("Content-Type", "application/json");
		HttpEntity entity = new StringEntity(param.toString(), StandardCharsets.UTF_8.name());
		post.setEntity(entity);
		
		String result = executeInternal(post);
		LOGGER.error("url【{}】请求参数【{}】,返回结果【{}】", url, param.toString(),result);
		if (StringUtil.isBlank(result)) {
			return emptyJson();
		}
		
		JSONObject repJson = JSONObject.parseObject(result);
		if (getData) {
			return repJson.getJSONObject("data");
		}
		return repJson;
	}
	
	private static JSONObject emptyJson() {
		JSONObject json = new JSONObject();
		json.put("RESULT", "-999");
		json.put("MSG", "API接口无返回");
		return json;
	}

	public static String executeInternal(HttpUriRequest request) {

		try (CloseableHttpClient httpclient = HttpClients.custom().build();) {
			try (CloseableHttpResponse response = httpclient.execute(request);) {
				int statusCode = response.getStatusLine().getStatusCode();
				if (HttpStatus.SC_OK == statusCode) {
					String result =  IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8.name());
					return result;
				}
				throw new RuntimeException(String.format("请求【%s】返回状态吗【%s】", request.getURI(), statusCode));
			}
		} catch (Exception e) {
			throw new RuntimeException(String.format("请求%s异常", request.getURI()),e);
		}
	}
}
